package com.heima.behavior.service.Impl;

import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
@Service
public class ApBehaviorEntryServiceImpl implements ApBehaviorEntryService {
    @Autowired
    MongoTemplate mongoTemplate;
    @Override
    public ApBehaviorEntry findByUserIdOrEquipmentId(Integer userId, Integer equipmentId) {
    if(userId!=null&&userId!=0){
        ApBehaviorEntry apBehaviorEntry = mongoTemplate.findOne(Query.query(Criteria.where("refId").is(userId).and("type").is(ApBehaviorEntry.Type.USER.getCode())), ApBehaviorEntry.class);
        if(apBehaviorEntry==null){
            ApBehaviorEntry behaviorEntry = new ApBehaviorEntry();
            behaviorEntry.setType(ApBehaviorEntry.Type.USER.getCode());
            behaviorEntry.setRefId(userId);
            behaviorEntry.setCreatedTime(new Date());
            mongoTemplate.save(behaviorEntry);
            return behaviorEntry;
        }
        return apBehaviorEntry;
    }
    if(equipmentId!=null&&equipmentId!=0){
        ApBehaviorEntry apBehaviorEntry = mongoTemplate.findOne(Query.query(Criteria.where("refId").is(equipmentId).and("type").is(ApBehaviorEntry.Type.EQUIPMENT.getCode())), ApBehaviorEntry.class);
        if(apBehaviorEntry==null){
            ApBehaviorEntry behaviorEntry = new ApBehaviorEntry();
            behaviorEntry.setType(ApBehaviorEntry.Type.EQUIPMENT.getCode());
            behaviorEntry.setRefId(equipmentId);
            behaviorEntry.setCreatedTime(new Date());
            mongoTemplate.save(behaviorEntry);
            return behaviorEntry;
        }
        return apBehaviorEntry;
    }
        return null;
    }
}
